<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/bootstrap.min.css">
<script src="/jquery.min.js"></script>
<script src="/bootstrap.min.js"></script>
<script src="/echarts.min.js"></script>
<title>自动打印系统</title>
</head>

<body style="background-color: rgba(248, 249, 250, 0.8); height: 100%;width:99%">

	<!-- 提示框  -->
	<div
		style="position: fixed; top: 20px; right: 20px; width: auto; z-index: 1">
		<div class="alert alert-success alert-dismissable" id="alertSuccess"
			hidden="true">
			<button type="button" class="close" data-dismiss="alert"
				aria-hidden="true">&times;</button>
			<span id="alertSuccessText"></span>
		</div>
	</div>
	<!-- 展示数据  -->
	<div style="height: 100%; z-index: 2">
		<div class="row"
			style="margin-right: 10px; height: 40%; margin-left: 10px; margin-top: 10px;">
			<!-- 打印机联网状态饼状图 -->

			<div class="col-4" style="margin-right: 0px; padding-right: 0px;">
				<div id="offLine" style="height: 300px; background-color: #ffffff;"></div>
			</div>
			<!-- 打印机故障状态饼状图 -->
			<div class="col-4" style="margin-right: 0px; padding-right: 0px;">
				<div id="error" style="height: 300px; background-color: #ffffff;"></div>
			</div>
			<!-- 打印机运行状态饼状图 -->
			<div class="col-4">
				<div id="job" style="height: 300px; background-color: #ffffff;"></div>
			</div>
		</div>

		<div
			style="margin: 30px 10px 10px 10px; height: 60%; background-color: #ffffff">
			<!-- 打印机控制按钮 -->
			<div class="row" style="padding: 10px 10px 10px 10px">
				<div class="col">
					<!-- 启动所有打印机按钮 -->
					<button onclick="startAll()" class="btn-sm btn-primary"
						style="width: 100%">启动所有打印机</button>
				</div>
				<div class="col">
					<!-- 关闭所有打印机按钮 -->
					<button onclick="stopAll()" class="btn-sm btn-warning"
						style="width: 100%">关闭所有打印机</button>
				</div>
			</div>
			<!-- 打印机状态监控表格 -->
			<div
				style="overflow-y: auto; height: 100%; margin-top: 10px; background-color: #ffffff;">
				<table class="table table-hover table-striped">
					<thead class="thead-light">
						<tr>
							<th scope="col">序号</th>
							<th scope="col">平台编码</th>
							<th scope="col">任务区间</th>
							<th scope="col">打印机IP</th>
							<th scope="col">在线状态</th>
							<th scope="col">纸剩余</th>
							<th scope="col">故障状态</th>
							<th scope="col">上盖</th>
							<th scope="col">切刀</th>
							<th scope="col">打印头状态</th>
							<th scope="col">工作</th>
							<th scope="col">操作</th>
						</tr>
					</thead>
					<tbody id="allStatus">
					</tbody>
				</table>
			</div>
		</div>
	</div>
</body>

<!-- javaScript代码 -->
<script type="text/javascript">
	let hostname = location.hostname;
	let port = location.port;
    // 提示工具
    function tip(text) {
        document.getElementById('alertSuccessText').innerText = text;
        document.getElementById('alertSuccess').removeAttribute('hidden');
        setTimeout(function () {
            document.getElementById('alertSuccess').setAttribute('hidden','true');
        },2000);
    }

    // 启动所有打印机
    function startAll() {
        $.post("http://"+hostname+":"+port+"/printer/start", function (data) {
            if (data === true || data === 'true') {
                tip('成功发送启动所有打印机命令');
            }else{
                tip('发送启动所有打印机命令失败');
            }
        });
    }

    // 关闭所有打印机
    function stopAll() {
        $.post("http://"+hostname+":"+port+"/printer/stop", function (data) {
            if (data === true || data === 'true') {
                tip('成功发送关闭所有打印机命令');
            }else{
                tip('发送关闭所有打印机命令失败');
            }
        });
    }

    // 启动IP为ip的打印机
    function start(ip) {
        $.post("http://"+hostname+":"+port+"/printer/start/" + ip, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送启动打印机' + ip + '命令');
            }else{
                tip('发送启动打印机' + ip + '命令失败');
            }
        });
    }

    // 关闭IP为ip的打印机
    function stop(ip) {
        $.post("http://"+hostname+":"+port+"/printer/stop/" + ip, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送关闭打印机' + ip + '命令');
            }else{
                tip('发送关闭打印机' + ip + '命令失败');
            }
        });
    }

    // 联网图表
    let offLine = echarts.init(document.getElementById('offLine'));
    let offLineOption = [
        {value: 0, name: '在线'},
        {value: 1, name: '离线'},
    ];

    // 故障图表
    let error = echarts.init(document.getElementById('error'));
    let errorOption = [
        {value: 0, name: '正常'},
        {value: 0, name: '脱机'},
    ];

    // 运行图表
    let job = echarts.init(document.getElementById('job'));
    let jobOption = [
        {value: 0, name: '工作'},
        {value: 0, name: '空闲'},
    ];

    // 饼状图图表模板
    let option = {
        title: {
            text: '监控面板',
            subtext: "",
            left: 'left'
        },
        color: ["blue", "red", "green"],
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            left: 'right',
        },
        series: [
            {
                name: '打印机在线状态',
                type: 'pie',
                radius: '70%',
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                data: []
            }
        ]
    };

    // 初始化三个图表
    option.series[0].data = offLineOption;
    option.title.subtext = "联网0/离线0";
    option.title.text = "联网状态"
    offLine.setOption(option);
    option.series[0].data = errorOption;
    option.title.subtext = "正常0/脱机0";
    option.title.text = "脱机状态"
    error.setOption(option);
    option.series[0].data = jobOption;
    option.title.subtext = "运行0/空闲0";
    option.title.text = "工作状态"
    job.setOption(option);

    // 记录所有打印机的信息
    let ips = [];
    let warehouse = [];
    let stockCode = [];
    let onlinePrinter = [], normalPrinter = [], workingPrinter = [];
    let allStatus = {};
    // websocket服务
    let websocket = new WebSocket('ws://' + hostname + ':' + port + '/websocket/index');
    
    // 移除”打印其他库区“，ip1为被移除打印机，ip2为当前库区打印机
    function removeIP(ip1, ip2) {
        $.post("http://"+hostname+":"+port+"/printer/remove/" + ip1 + "/" + ip2, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送移除打印机'+ip2+'命令');
            }
        })
    }

    // 添加“打印其他库区”，ip1为被添加打印机，ip2为当前库区打印机
    function addIP(ip1, ip2) {
        $.post("http://"+hostname+":"+port+"/printer/add/" + ip1 + "/" + ip2, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送添加打印机'+ip2+'命令');
            }
        })
    }
    
    // 重新打印
    function rePrint(ip, msgId){
    	$.post("http://"+hostname+":"+port+"/printer/reprint/" + ip + "/" + msgId, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送重新打印'+msgId+'命令');
            }
        })
    }

    // 更新所有打印机的状态图表
    function updateAllStatus(ip, status) {
        let data = "";
        let index = 0;
        	allStatus[ip] = status;
        	normalPrinter.forEach(function (item) {
            if (workingPrinter.includes(item)) {
				index = index + 1;
                data = data + '<tr><td>' + index + '</td>'
                	+ '<td>' + warehouse[ips.indexOf(item)] + '</td>'    
                	+ '<td><a href="/printer/' + item + '">' + stockCode[ips.indexOf(item)] + '</a></td>'
                    + '<td>' + item + '</td>'
                    + '<td><span class="badge badge-success">在线</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    // + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">运行中</span></td>'
                    + '<td><button type="button" onclick="stop(\'' + item + '\')" class="btn btn-warning btn-sm">终止</button></td>'
                    + '</tr>';
            }
        });
        
        normalPrinter.forEach(function (item) {
            if (!workingPrinter.includes(item)) {
				index = index + 1;
                data = data + '<tr><td>' + index + '</td>'
	                + '<td>' + warehouse[ips.indexOf(item)] + '</td>'    
	            	+ '<td><a href="/printer/' + item + '">' + stockCode[ips.indexOf(item)] + '</a></td>'
                    + '<td>' + item + '</td>'
                    + '<td><span class="badge badge-success">在线</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    // + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge badge-success">正常</span></td>'
                    + '<td><span class="badge bg-info text-dark">空闲</span></td>'
                    + '<td><button type="button" onclick="start(\'' + item + '\')" class="btn btn-primary btn-sm">启动</button></td>'
                    + '</tr>';
            }
        });
        
        onlinePrinter.forEach(function (item) {
            if (!normalPrinter.includes(item)) {
				index = index + 1;
            		data = data + '<tr><td>' + index + '</td>'
			                + '<td>' + warehouse[ips.indexOf(item)] + '</td>'    
			            	+ '<td><a href="/printer/' + item + '">' + stockCode[ips.indexOf(item)] + '</a></td>'
							+ '<td>' + item + '</td>'
							+ '<td><span class="badge badge-success">在线</span></td>'
							+ '<td><span class="badge badge-' + ((allStatus[item].paperDo==='true' || allStatus[item].paperDo===true) ? 'danger">用尽' : 'success">充足') + '</span></td>'
							+ '<td><span class="badge bg-danger">故障</span></td>'
							// + '<td id="' + item + 'paper"><span class="badge badge-success">正常</span></td>'
							+ '<td><span class="badge badge-' + ((allStatus[item].cover==='true' || allStatus[item].cover===true) ? 'danger">故障' : 'success">正常') + '</span></td>'
							+ '<td><span class="badge badge-' + ((allStatus[item].cutter==='true' || allStatus[item].cutter===true) ? 'danger">故障' : 'success">正常') + '</span></td>'
							+ '<td><span class="badge badge-' + ((allStatus[item].temperatureAndVoltage==='true' || allStatus[item].temperatureAndVoltage===true) ? 'danger">超出范围' : 'success">正常') + '</span></td>'
							+ '<td><span class="badge bg-secondary">/</span></td>'
							+ '<td><span class="badge bg-secondary">/</span></td>'
							+ '</tr>';
            }
        
        });
        
        ips.forEach(function (item) {
            if (!onlinePrinter.includes(item)) {
				index = index + 1;
                data = data + '<tr><td>' + index + '</td>'
	                + '<td>' + warehouse[ips.indexOf(item)] + '</td>'    
	            	+ '<td><a href="/printer/' + item + '">' + stockCode[ips.indexOf(item)] + '</a></td>'
                    + '<td>' + item + '</td>'
                    + '<td><span class="badge badge-danger">离线</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '<td><span class="badge bg-secondary">/</span></td>'
                    + '</tr>';
            }
        });
        document.getElementById("allStatus").innerHTML = data;
    }

    // 更新联网状态饼状图
    function updateOffLineChart() {
        offLineOption[0].value = onlinePrinter.length;
        offLineOption[1].value = ips.length - onlinePrinter.length;
        option.series[0].data = offLineOption;
        option.title.text = "联网状态";
        option.title.subtext = "联网" + onlinePrinter.length + "/离线" + (ips.length - onlinePrinter.length);
        option.color = ["blue", "red"];
        offLine.setOption(option);
    }

    // 更新故障状态饼状图
    function updateErrorChart() {
        errorOption[0].value = normalPrinter.length;
        errorOption[1].value = onlinePrinter.length - normalPrinter.length;
        option.series[0].data = errorOption;
        option.title.text = "脱机状态";
        option.color = ["blue", "#ffc107"];
        option.title.subtext = "正常" + normalPrinter.length + "/离线" + (normalPrinter.length - normalPrinter.length);
        error.setOption(option);
    }

    //更新运行状态饼状图
    function updateJobChart() {
        jobOption[0].value = workingPrinter.length;
        jobOption[1].value = normalPrinter.length - workingPrinter.length;
        option.series[0].data = jobOption;
        option.title.text = "工作状态"
        option.color = ["blue", "green"];
        option.title.subtext = "运行" + workingPrinter.length + "/空闲" + (onlinePrinter.length - workingPrinter.length);
        job.setOption(option);
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        console.log("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("WebSocket连接成功");
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("连接关闭")
        websocket = new WebSocket("ws://"+hostname+":"+port+"/websocket/index");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    // 接收到消息的回调方法
    websocket.onmessage = function (event) {
        const data = JSON.parse(event.data);
        if (data.code === 0) {
            // 获取所有打印机
            ips = data.ips;
            warehouse = data.warehouse;
            stockCode = data.stockCode;
            updateOffLineChart();
            updateErrorChart();
            updateJobChart();
			updateAllStatus('192.0.0.0', "status");
        } else if (data.code === 1 || data.code === '1') {
            // 更新联网面板数据
            if (onlinePrinter.includes(data.ip) && (data.offline === true || data.offline === 'true')) {
                let temp = [];
                onlinePrinter.forEach(function (d) {
                    if (d !== data.ip) {
                        temp.push(d);
                    }
                });
                onlinePrinter = temp;
                temp = [];
                if(normalPrinter.includes(data.ip)){
                    normalPrinter.forEach(function (d) {
                        if (d !== data.ip) {
                            temp.push(d);
                        }
                    });
                    normalPrinter = temp;
                }
                temp = [];
                if(workingPrinter.includes(data.ip)){
                    workingPrinter.forEach(function (d) {
                        if (d !== data.ip) {
                            temp.push(d);
                        }
                    });
                    workingPrinter = temp;
                }
            }
            if (!onlinePrinter.includes(data.ip) && (data.offline === false || data.offline === 'false')) {
                onlinePrinter.push(data.ip);
            }

            // 更新脱机面板数据
            if (normalPrinter.includes(data.ip) && (data.esc.status.offLine === true || data.esc.status.offLine === 'true')) {
                let temp = [];
                normalPrinter.forEach(function (d) {
                    if (d !== data.ip) {
                        temp.push(d);
                    }
                });
                normalPrinter = temp;
                temp = [];
                if(workingPrinter.includes(data.ip)){
                    workingPrinter.forEach(function (d) {
                        if (d !== data.ip) {
                            temp.push(d);
                        }
                    });
                    workingPrinter = temp;
                }
            }
            if (!normalPrinter.includes(data.ip) && onlinePrinter.includes(data.ip) && (data.esc.status.offLine === false || data.esc.status.offLine === 'false')) {
                normalPrinter.push(data.ip);
            }

            // 更新工作面板数据
            if (workingPrinter.includes(data.ip) && (data.run === false || data.run === 'false')) {
                const temp = [];
                workingPrinter.forEach(function (d) {
                    if (d !== data.ip) {
                        temp.push(d);
                    }
                });
                workingPrinter = temp;
            }
            if (!workingPrinter.includes(data.ip) && onlinePrinter.includes(data.ip) && (data.run === true || data.run === 'true')) {
                workingPrinter.push(data.ip);
            }
            
            updateOffLineChart();
            updateErrorChart();
            updateJobChart();
            updateAllStatus(data.ip, data.esc.status);
        }

    }

</script>
</html>